var fs = require("fs");

var Application = function() {
	this._data = {};
	this._id = null;
	this._file = null;

	this._name = Config.applicationFileName || "v8cgi-application.data";
	this._path = Config.applicationPath || "/tmp";
	if (this._path.charAt(this._path.length-1) != "/") { this._path += "/"; }
        this._fileName = this._path + this._name;

        this._file = new fs.File(this._fileName);
        if (this._file.exists()) {
	    this._load();
	}
	
	var self = this;
	var callback = function() { self.save(); }
	onexit(callback);
}

Application.prototype.set = function(name, value) {
	this._data[name] = value;
}

Application.prototype.get = function(name) {
	return this._data[name] || null;
}

Application.prototype.clear = function() {
	this._data = {};
	if (this._file.exists()) { this._file.remove(); }
}

Application.prototype.save = function() {
	var propcnt = 0;
	for (var p in this._data) { propcnt++; }
		if (propcnt == 0) {
		if (this._file.exists()) { this._file.remove(); }
		return;
	}
	var str = JSON.stringify(this._data);
	this._file.open("w").write(str).close();
}

Application.prototype._load = function() {
	var str = this._file.open("r").read().toString("utf-8");
	this._file.close();
	this._data = JSON.parse(str);
}

exports.Application = Application;
